<?php
/**
 * @package Freshine
 * @since Freshine 2.0.0
 */
 
/*-----------------------------------------------------------------------------------*/
/*	Add "Options Backup" submenu
/*-----------------------------------------------------------------------------------*/
add_action('admin_menu', 'f9_add_install_admin_submenus');
function f9_add_install_admin_submenus() {
	add_submenu_page('theme-options', 'Options Backup', 'Options Backup', 'manage_options', 'freshine-backup', 'f9_install_options_admin');
}

function f9_install_options_admin() { ?>
<div class="wrap">
	<?php screen_icon('options-general'); ?>
	<h2>Freshine Import/Export</h2>
	<?php if(isset($_POST['save'])&&$_POST['save']=='Import') :
	$uploads = wp_upload_dir();
	$target_path = $uploads['path'] . '/' . basename( $_FILES['import']['name']); 
	if(move_uploaded_file($_FILES['import']['tmp_name'], $target_path)) {
		$file_content = file_get_contents($target_path, true);
		f9_import($file_content);
	} else {
		echo "There was an error uploading the file, please try again!";
	}
	
	elseif(isset($_POST['save'])&&$_POST['save']=='Export') :
		f9_export();
	else: ?>
	<h3 class="title">Import</h3>
	<form method="post" enctype="multipart/form-data">
	<p>Howdy! Upload your Freshine eXtended RSS (FXR) file and we'll import the <strong>Widgets, Options</strong> into this site.</p>
	<p>Choose a FXR (.xml) file to upload, then click Upload file and import.</p>
	<p>
		<label for="upload">Choose a file from your computer: (Maximum size: 80MB)
		<input type="file" size="25" name="import" id="upload"></label>
		<input type="hidden" value="83886080" name="max_file_size">
	</p>
	<p class="submit">
		<input type="submit" class="button-primary" value="Import" name="save">
		<input type="hidden" value="save" name="action">
	</p>
	</form>
	<h3 class="title">Export</h3>
	<form method="post">
	<p>When you click the button below Freshine will create an XML file for you to save to this dir:<br /><strong><?php echo STYLESHEETPATH; ?>/freshine-option.xml</strong></p>
	<p>This format, which we call Freshine eXtended RSS or FXR, will contain <strong>Widgets, Options</strong>.</p>
	<p>Once you've saved the download file, you can use the Freshine Import function in another WordPress installation to import this site.</p>
	<p class="submit">
		<input type="submit" class="button-primary" value="Export" name="save">
		<input type="hidden" value="save" name="action">
	</p>
	</form>
	<?php endif; ?>
</div>
<?php }

/*-----------------------------------------------------------------------------------*/
/*	Import running
/*-----------------------------------------------------------------------------------*/
function f9_import($file_content) {
	global $wpdb;
	if($file_content) {
		/*/Import users
		preg_match_all("/<user>(.*?)<\/user>/is", $file_content, $users);
		$user_fields = array('user:login', 'user:email', 'user:display_name', 'user:first_name', 'user:last_name', 'user:description');
		foreach($users[1] as $user) {
			$single_user = '';
			foreach($user_fields as $user_field) {
				preg_match("/<".$user_field.">(.*?)<\/".$user_field.">/is", $user, $single_user_field);
				$single_user[] = $single_user_field[1];
			}
			$user_data = array(
				'user_login' => $single_user[0],
				'user_pass' => wp_generate_password(),
				'user_email' => $single_user[1],
				'display_name' => $single_user[2],
				'first_name' => $single_user[3],
				'last_name' => $single_user[4],
				'description' => $single_user[5],
			);
			wp_insert_user( $user_data );
		}
		
		//Import categories
		preg_match_all("/<category>(.*?)<\/category>/is", $file_content, $categories);
		$category_fields = array('category:name', 'category:slug', 'category:description', 'category:id', 'category:parent');
		foreach($categories[1] as $category) {
			$single_category = '';
			foreach($category_fields as $category_field) {
				preg_match("/<".$category_field.">(.*?)<\/".$category_field.">/is", $category, $single_category_field);
				$single_category[] = $single_category_field[1];
			}
			$category_data = array(
				'cat_name' => $single_category[0],
				'category_nicename' => $single_category[1],
				'category_description' => $single_category[2],
				//'cat_ID' => $single_category[3],
				'category_parent' => $single_category[4],
			);
			wp_insert_category( $category_data );
		}

		//Import tags
		preg_match_all("/<tag>(.*?)<\/tag>/is", $file_content, $tags);
		$tag_fields = array('tag:name', 'tag:slug');
		foreach($tags[1] as $tag) {
			$single_tag = '';
			foreach($tag_fields as $tag_field) {
				preg_match("/<".$tag_field.">(.*?)<\/".$tag_field.">/is", $tag, $single_tag_field);
				$single_tag[] = $single_tag_field[1];
			}
			wp_insert_term(
			$single_tag[0],
			'tag',
				array(
				'slug' => $single_tag[1]
				)
			);
		}
		
		//Import posts
		preg_match_all("/<post>(.*?)<\/post>/is", $file_content, $posts);
		$post_fields = array('post:title', 'post:content', 'post:excerpt', 'post:author', 'post:date', 'post:type', 'post:id', 'post:parent');
		foreach($posts[1] as $post) {
			$single_post = '';
			foreach($post_fields as $post_field) {
				preg_match("/<".$post_field.">(.*?)<\/".$post_field.">/is", $post, $single_post_field);
				$single_post[] = $single_post_field[1];
			}
			// Create post object
			$my_post = array(
				'ID' => $single_post[6],
				'post_title' => $single_post[0],
				'post_content' => $single_post[1],
				'post_excerpt' => $single_post[2],
				'post_author' => $single_post[3],
				'post_date' => $single_post[4],
				'post_type' => $single_post[5],
				'post_status' => 'publish',
				'post_parent' => $single_post[7]
			);
			
			// Insert the post into the database
			$post_id = wp_insert_post( $my_post );
			
			// Set post terms (category, tag, custom taxonomy)
			preg_match_all("/<post:term>(.*?)<\/post:term>/is", $post, $terms);
			$term_fields = array('post:term_name', 'post:term_taxonomy');
			foreach($terms[1] as $term) {
				$single_term = '';
				foreach($term_fields as $term_field) {
					preg_match("/<".$term_field.">(.*?)<\/".$term_field.">/is", $term, $single_term_field);
					$single_term[] = $single_term_field[1];
				}
				wp_set_object_terms( $post_id, $single_term[0], $single_term[1] );
			}
			
			// Insert post attachments
			preg_match_all("/<post:attachment>(.*?)<\/post:attachment>/is", $post, $attachments);
			$attachment_fields = array('post:attachment_type', 'post:attachment_url', 'post:attachment_thumbnail');
			foreach($attachments[1] as $attachment) {
				$single_attachment = '';
				foreach($attachment_fields as $attachment_field) {
					preg_match("/<".$attachment_field.">(.*?)<\/".$attachment_field.">/is", $attachment, $single_attachment_field);
					$single_attachment[] = $single_attachment_field[1];
				}
				
				//Copy image
				$uploads = wp_upload_dir();
				$filename = $uploads['path'] . '/' . basename(get_bloginfo('stylesheet_directory').'/images/sample-images/'.$single_attachment[1]);
				copy(get_bloginfo('stylesheet_directory').'/images/sample-images/'.$single_attachment[1], $filename);

				$wp_filetype = wp_check_filetype(basename($filename), null );
				$attachment_arr = array(
					'post_mime_type' => $single_attachment[0],
					'post_title' => preg_replace('/\.[^.]+$/', '', basename($filename)),
					'post_content' => '',
					'post_status' => 'inherit'
				);
				$attach_id = wp_insert_attachment( $attachment_arr, $filename, $post_id );
				require_once(ABSPATH . 'wp-admin/includes/image.php');
				$attach_data = wp_generate_attachment_metadata( $attach_id, $filename );
				wp_update_attachment_metadata( $attach_id, $attach_data );
				if($single_attachment[2]==1) {
					update_post_meta( $post_id,'_thumbnail_id',$attach_id);
				}
			}
			
			// Insert post metas
			preg_match_all("/<post:meta>(.*?)<\/post:meta>/is", $post, $metas);
			$meta_fields = array('post:meta_key', 'post:meta_value');
			foreach($metas[1] as $meta) {
				$single_meta = '';
				foreach($meta_fields as $meta_field) {
					preg_match("/<".$meta_field.">(.*?)<\/".$meta_field.">/is", $meta, $single_meta_field);
					$single_meta[] = $single_meta_field[1];
				}
				update_post_meta( $post_id, $single_meta[0], $single_meta[1]);
			}
			
			// Insert post comments			
			preg_match_all("/<post:comment>(.*?)<\/post:comment>/is", $post, $comments);
			$comment_fields = array('post:comment_author', 'post:comment_author_email', 'post:comment_author_url', 'post:comment_author_IP', 'post:comment_date_gmt', 'post:comment_content', 'post:comment_approved', 'post:comment_type', 'post:comment_parent');
			foreach($comments[1] as $comment) {
				$single_comment = '';
				foreach($comment_fields as $comment_field) {
					preg_match("/<".$comment_field.">(.*?)<\/".$comment_field.">/is", $comment, $single_comment_field);
					$single_comment[] = $single_comment_field[1];
				}
				$comment_user = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->users WHERE user_login = '".$single_comment[0]."'" ) );
				if($comment_user){
					$comment_user = $comment_user->ID;
				} else {
					$comment_user = NULL;
				}
				$comment_data = array(
					'comment_post_ID' => $post_id,
					'comment_author' => $single_comment[0],
					'comment_author_email' => $single_comment[1],
					'comment_author_url' => $single_comment[2],
					'comment_author_IP' => $single_comment[3],
					'comment_date_gmt' => $single_comment[4],
					'comment_content' => $single_comment[5],
					'comment_approved' => $single_comment[6],
					'comment_type' => $single_comment[7],
					'comment_parent' => $single_comment[8],
					'user_id' => $comment_user,
				);
				wp_insert_comment($comment_data);
			}
		}
		
		// Import menus
		preg_match_all("/<menu>(.*?)<\/menu>/is", $file_content, $menus);
		$menu_fields = array('menu:title', 'menu:position', 'menu:order', 'menu:object', 'menu:object_name', 'menu:url', 'menu:type', 'menu:id', 'menu:parent');
		foreach($menus[1] as $menu) {
			$single_menu = '';
			foreach($menu_fields as $menu_field) {
				preg_match("/<".$menu_field.">(.*?)<\/".$menu_field.">/is", $menu, $single_menu_field);
				$single_menu[] = $single_menu_field[1];
			}
			
			// Create post object
			if($single_menu[0]) {
				$menu_title = $single_menu[0];
			} else {
				$menu_title = $single_menu[4];
			}
			$my_menu = array(
				'ID' => $single_menu[7],
				'post_title' => $menu_title,
				'menu_order' => $single_menu[2],
				'post_type' => 'nav_menu_item',
				'post_status' => 'publish',
				'post_parent' => $single_menu[8]
			);
			
			// Insert the post into the database
			$post_id = wp_insert_post( $my_menu );
			//Menu type
			wp_set_object_terms( $post_id, $single_menu[1], 'nav_menu' );
			update_post_meta( $post_id, '_menu_item_url', $single_menu[5]);
			
			if($single_menu[3]) {
				update_post_meta( $post_id, '_menu_item_object', $single_menu[3]);
			} else {
				update_post_meta( $post_id, '_menu_item_object', 'custom');
				
			}
			if($single_menu[6]=='taxonomy') {
				$object_id = get_term_by( 'name', $single_menu[4], $single_menu[3] );
				update_post_meta( $post_id, '_menu_item_object_id', $object_id->term_id);
			} else {
				$post = $wpdb->get_var( $wpdb->prepare( "SELECT ID FROM $wpdb->posts WHERE post_title = %s", $single_menu[4] ));
				update_post_meta( $post_id, '_menu_item_object_id', $post);
			}
			update_post_meta( $post_id, '_menu_item_type', $single_menu[6]);
		}*/
		
		// Import widgets
		preg_match_all("/<widget>(.*?)<\/widget>/is", $file_content, $widgets);
		$widget_fields = array('widget:type', 'widget:value');
		foreach($widgets[1] as $widget) {
			$single_widget = '';
			foreach($widget_fields as $widget_field) {
				preg_match("/<".$widget_field.">(.*?)<\/".$widget_field.">/is", $widget, $single_widget_field);
				$single_widget[] = $single_widget_field[1];
			}
			$wpdb->query("UPDATE $wpdb->options SET `option_value` = '".$single_widget[1]."' WHERE `option_name` = '".$single_widget[0]."' LIMIT 1 ;");
		}
		
		// Import options
		preg_match_all("/<option>(.*?)<\/option>/is", $file_content, $options);
		$option_fields = array('option:name', 'option:value');
		foreach($options[1] as $option) {
			$single_option = '';
			foreach($option_fields as $option_field) {
				preg_match("/<".$option_field.">(.*?)<\/".$option_field.">/is", $option, $single_option_field);
				$single_option[] = $single_option_field[1];
			}
			$wpdb->query("UPDATE $wpdb->options SET `option_value` = '".$single_option[1]."' WHERE `option_name` = '".$single_option[0]."' LIMIT 1 ;");
		}
		echo "Import completed!";
	} else {
		echo "Can't read your file!";
	}
}

/*-----------------------------------------------------------------------------------*/
/*	Export running
/*-----------------------------------------------------------------------------------*/
function f9_export() {
	$file = fopen(STYLESHEETPATH."/freshine-option.xml","w");
	$file_content = '<xml version="1.0" encoding="utf-8"?>
<freshine>';
	global $wpdb;
	/*/Export users
	$users = get_users('orderby=id');
    foreach ($users as $user) {
	$file_content.= '
	<user>
		<user:login>'.$user->user_login.'</user:login>
		<user:nicename>'.$user->user_nicename.'</user:nicename>
		<user:email>'.$user->user_email.'</user:email>
		<user:display_name>'.$user->display_name.'</user:display_name>
		<user:first_name>'.get_user_meta($user->ID, 'first_name', true).'</user:first_name>
		<user:last_name>'.get_user_meta($user->ID, 'last_name', true).'</user:last_name>
		<user:description>'.get_user_meta($user->ID, 'description', true).'</user:description>
	</user>';
    }
	//Export categories
	$categories = get_categories(); 
	foreach ($categories as $category) {
	$file_content.= '
	<category>
		<category:name>'.$category->name.'</category:name>
		<category:slug>'.$category->slug.'</category:slug>
		<category:description>'.$category->category_description.'</category:description>
		<category:id>'.$category->cat_ID.'</category:id>
		<category:parent>'.$category->category_parent.'</category:parent>
	</category>';
	}
	//Export tags
	$tags = get_tags();
	foreach ($tags as $tag) {
	$file_content.= '
	<tag>
		<tag:name>'.$tag->name.'</tag:name>
		<tag:slug>'.$tag->slug.'</tag:slug>
	</tag>';
	}
	//Export posts
	$posts = get_posts( array('numberposts' => -1, 'post_type' => array('post', 'page', 'slide', 'forum', 'topic', 'reply')) );
	foreach ($posts as $post) {
	$file_content.= '
	<post>
		<post:title>'.$post->post_title.'</post:title>
		<post:content>'.$post->post_content.'</post:content>
		<post:excerpt>'.$post->post_excerpt.'</post:excerpt>
		<post:author>'.$post->post_author.'</post:author>
		<post:date>'.$post->post_date.'</post:date>
		<post:type>'.$post->post_type.'</post:type>';
	//Export post terms
	$relationships = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->term_relationships WHERE object_id = %d", $post->ID ) );
	foreach( $relationships as $relationship ) :
		$term_taxonomies = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->term_taxonomy LEFT JOIN $wpdb->terms ON $wpdb->term_taxonomy.term_id = $wpdb->terms.term_id WHERE $wpdb->term_taxonomy.term_taxonomy_id = %d", $relationship->term_taxonomy_id ) );
		foreach( $term_taxonomies as $term_taxonomy ) :
		$file_content.= '
		<post:term>
			<post:term_name>'.$term_taxonomy->name.'</post:term_name>
			<post:term_taxonomy>'.$term_taxonomy->taxonomy.'</post:term_taxonomy>
		</post:term>';
		endforeach;
	endforeach;
	//Export post attachments
$attachments = get_posts(array( 'post_type' => 'attachment', 'numberposts' => -1, 'post_status' => null, 'post_parent' => $post->ID ));
$attachment_thumbnail_id = $wpdb->get_row( $wpdb->prepare( "SELECT * FROM $wpdb->postmeta WHERE post_id = ".$post->ID." AND meta_key = '_thumbnail_id';" ) );
if ($attachments) {
	foreach ( $attachments as $attachment ) {
		$image_attribute = wp_get_attachment_image_src( $attachment->ID , true );
		if($attachment->ID == $attachment_thumbnail_id->meta_value) {
			$attachment_thumbnail = '1';
		} else {
			$attachment_thumbnail = '0';
		}
		//Check upload folder
		$upload_folder = STYLESHEETPATH . '/images/sample-images/';
		if( file_exists($upload_folder) == false ) {
			chmod( STYLESHEETPATH . "/images/", 0755);
			mkdir($upload_folder);
			chmod($upload_folder, 0755);
		}
		//Copy image
		$filename = STYLESHEETPATH . '/images/sample-images/' . basename($image_attribute[0]);
		copy($image_attribute[0], $filename);
		
		$file_content.= '
		<post:attachment>
			<post:attachment_type>' .$attachment->post_mime_type.'</post:attachment_type>
			<post:attachment_url>' .basename($image_attribute[0]).'</post:attachment_url>
			<post:attachment_thumbnail>' .$attachment_thumbnail.'</post:attachment_thumbnail>
		</post:attachment>';
	}
}
	//Export post meta
$postmeta = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->postmeta WHERE post_id = %d", $post->ID ) );
	foreach( $postmeta as $meta ) : if ( $meta->meta_key != '_edit_lock' && $meta->meta_key != '_edit_last' && $meta->meta_key != '_wp_old_slug' && $meta->meta_key != '_thumbnail_id' ) :
		$file_content.='
		<post:meta>
			<post:meta_key>'.$meta->meta_key.'</post:meta_key>
			<post:meta_value>'.$meta->meta_value.'</post:meta_value>
		</post:meta>';
	endif; endforeach;
	//Export comments
$comments = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->comments WHERE comment_post_ID = %d AND comment_approved <> 'spam'", $post->ID ) );
		foreach ( $comments as $c ) :
		$file_content.= '
		<post:comment>
			<post:comment_author>'.$c->comment_author.'</post:comment_author>
			<post:comment_author_email>'.$c->comment_author_email.'</post:comment_author_email>
			<post:comment_author_url>'.$c->comment_author_url.'</post:comment_author_url>
			<post:comment_author_IP>'.$c->comment_author_IP.'</post:comment_author_IP>
			<post:comment_date_gmt>'.$c->comment_date_gmt.'</post:comment_date_gmt>
			<post:comment_content>'.$c->comment_content.'</post:comment_content>
			<post:comment_approved>'.$c->comment_approved.'</post:comment_approved>
			<post:comment_type>'.$c->comment_type.'</post:comment_type>
			<post:comment_parent>'.$c->comment_parent.'</post:comment_parent>
		</post:comment>';
	endforeach;
	$file_content.= '
		<post:id>'.$post->ID.'</post:id>
		<post:parent>'.$post->post_parent.'</post:parent>
	</post>';
	}
	
	//Export menus
	$posts = get_posts( array('numberposts' => -1, 'post_type' => array('nav_menu_item')) );
	foreach ($posts as $post) {
	$file_content.= '
	<menu>
		<menu:title>'.$post->post_title.'</menu:title>';
	//Export menu types
	$relationships = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->term_relationships WHERE object_id = %d", $post->ID ) );
	foreach( $relationships as $relationship ) :
		$term_taxonomies = $wpdb->get_results( $wpdb->prepare( "SELECT * FROM $wpdb->term_taxonomy LEFT JOIN $wpdb->terms ON $wpdb->term_taxonomy.term_id = $wpdb->terms.term_id WHERE $wpdb->term_taxonomy.term_taxonomy_id = %d", $relationship->term_taxonomy_id ) );
		foreach( $term_taxonomies as $term_taxonomy ) :
		$file_content.= '
		<menu:position>'.$term_taxonomy->name.'</menu:position>';
		endforeach;
	endforeach;
	$file_content.= '
		<menu:order>'.$post->menu_order.'</menu:order>';
	if(get_post_meta($post->ID, '_menu_item_type', true)=='post_type') {
		$post_type = get_post(get_post_meta($post->ID, '_menu_item_object_id', true)); 
		$file_content.= '
		<menu:object>'.get_post_meta($post->ID, '_menu_item_object', true).'</menu:object>
		<menu:object_name>'.$post_type->post_title.'</menu:object_name>';
	} elseif(get_post_meta($post->ID, '_menu_item_type', true)=='taxonomy') {
		$term = get_term( get_post_meta($post->ID, '_menu_item_object_id', true), get_post_meta($post->ID, '_menu_item_object', true) );
		$file_content.= '
		<menu:object>'.get_post_meta($post->ID, '_menu_item_object', true).'</menu:object>
		<menu:object_name>'.$term->name.'</menu:object_name>';
	} else {
		$file_content.= '
		<menu:url>'.get_post_meta($post->ID, '_menu_item_url', true).'</menu:url>';
	}
	$file_content.= '
		<menu:type>'.get_post_meta($post->ID, '_menu_item_type', true).'</menu:type>
		<menu:id>'.$post->ID.'</menu:id>
		<menu:parrent>'.$post->post_parent.'</menu:parrent>
	</menu>';
	}*/
	
	//Export widgets
	$widgets = $wpdb->get_results( "SELECT * FROM $wpdb->options WHERE `option_name` LIKE 'widget_%'" );
	foreach ($widgets as $widget) {
	$file_content.= '
	<widget>
		<widget:type>'.$widget->option_name.'</widget:type>
		<widget:value>'.$widget->option_value.'</widget:value>
	</widget>';
	}
	//Export options
	$theme = get_option( 'stylesheet' );
	$option_fields = array('sidebars_widgets', 'nav_menu_options', 'theme_mods_'.$theme);
	foreach ($option_fields as $option_field) {
		$option = $wpdb->get_row( "SELECT * FROM $wpdb->options WHERE `option_name` = '".$option_field."'" );
		$file_content.= '
	<option>
		<option:name>'.$option_field.'</option:name>
		<option:value>'.$option->option_value.'</option:value>
	</option>';
	}
	
	$file_content.= '
</freshine>';
fwrite($file, $file_content);
fclose($file);
echo "Export to <strong>".STYLESHEETPATH."/freshine-option.xml</strong> completed!";
}